﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Transactions;
namespace BLL
{


    public class QLTaiKhoan
    {
        public static IEnumerable<TaiKhoan> GetAll()
        {
            return Generic.GetAll<TaiKhoan>();
        }

        public static ActionResult Insert(TaiKhoan tb)
        {
            ActionResult kq = new ActionResult();
            try
            {
                Generic.Insert<TaiKhoan>(tb);
            }
            catch (Exception ex)
            {
                kq.Exceptions.Add(ex);
            }
            return kq;
        }
        public static ActionResult Insert(ThongTinNguoiDung tt)
        {
            ActionResult kq = new ActionResult();
            try
            {
                Generic.Insert<ThongTinNguoiDung>(tt);
            }
            catch (Exception ex)
            {
                kq.Exceptions.Add(ex);
            }
            return kq;
        }
        /// <summary>
        /// test lỗi đơn giản.
        /// </summary>
        public static ActionResult TestError(TaiKhoan tk, ThongTinNguoiDung tt, string _mk2, string _loai)
        {
            ActionResult kq = new ActionResult();
            if (tk.MaTK == "")
                kq.Exceptions.Add(new Exception("Mã Tài Khoản Phải Khác rỗng."));
            if (_loai == "insert" && QLTaiKhoan.FindByCondition(x => x.MaTK == tk.MaTK).ToList().Count > 0)
                kq.Exceptions.Add(new Exception("Mã Tài Khoản Đã Tồn Tại."));
            if (tk.TenDangNhap == "")
                kq.Exceptions.Add(new Exception("Tên Tài Khoản Phải khác rỗng."));
            if (_loai == "insert" && QLTaiKhoan.FindByUserName(tk.TenDangNhap) != null)
                kq.Exceptions.Add(new Exception("Tên Tài Khoản Đã Tồn Tại."));
            if (tk.MatKhau == "")
                kq.Exceptions.Add(new Exception("Mật Khẩu Phải khác rỗng."));
            if (tk.MatKhau != _mk2)
                kq.Exceptions.Add(new Exception("nhập lại mật khẩu nhập không đúng"));
            if (tt.ChucVu == "")
            {
                kq.Exceptions.Add(new Exception("chưa chọn chức vụ"));
            }
            return kq;
        }
        /// <summary>
        /// Thêm Tài khoản.
        /// </summary>
        public static ActionResult Insert(TaiKhoan tk, ThongTinNguoiDung tt, string _mk2)
        {
            ActionResult kq = new ActionResult("Thêm Tài Khoản");
            kq.Exceptions.AddRange(TestError(tk, tt, _mk2, "insert").Exceptions);
            if (kq.Success)
            {
                try
                {
                    if (!Generic.Insert<TaiKhoan>(tk) || !Generic.Insert<ThongTinNguoiDung>(tt))
                        kq.Exceptions.Add(new Exception("lỗi"));
                }
                catch (Exception ex)
                {
                    kq.Exceptions.Add(ex);
                }
            }
            return kq;
        }
        /// <summary>
        /// Thêm Tài khoản và thêm phân quyền
        /// </summary>
        public static ActionResult Insert(TaiKhoan tk, ThongTinNguoiDung tt, string _mk2, List<PhanQuyenSuDung> dspqsd)
        {
            ActionResult kq = new ActionResult("Thêm Tài Khoản");
            kq.Exceptions.AddRange(TestError(tk, tt, _mk2, "insert").Exceptions);
            if (kq.Success)
            {
                using (var transaction = new TransactionScope())
                {

                    kq.Exceptions.AddRange(Insert(tk).Exceptions);
                    if (kq.Success)

                    {
                        kq.Exceptions.AddRange(Insert(tt).Exceptions);
                    }
                    if (kq.Success)
                    {
                        tt.MaTK = tk.MaTK;
                        kq.Exceptions.AddRange(QLPhanQuyenSuDung.UpdatePhanQuyen(tk.MaTK, dspqsd).Exceptions);
                    }
                    if (kq.Success)
                    {
                        transaction.Complete();
                    }
                    else
                    {
                        transaction.Dispose();
                      
                    }
                }
            }
            Generic.Reconnect();
            return kq;
        }
        /// <summary>
        /// Delete 1 tài khoản theo mã tk.
        /// </summary>
        public static int Delete(string MaTK)
        {
            return Generic.DeleteByCondition<TaiKhoan>(x => x.MaTK == MaTK);
        }
        /// <summary>
        /// Delete all tài khoản theo list
        /// tk.
        /// </summary>
        public static int DeleteAll(IEnumerable<TaiKhoan> ps)
        {
            Generic.DeleteByCondition<ThongTinNguoiDung>(tb => ps.Where(x => x.MaTK == tb.MaTK).Count() == 1);
            return Generic.DeleteByCondition<TaiKhoan>(tb => ps.Where(x => x.MaTK == tb.MaTK).Count() == 1);
        }
        /// <summary>
        /// Delete 1 tài khoản theo list mã tk.
        /// </summary>
        public static int DeleteAll(IEnumerable<string> MaTK)
        {
            Generic.DeleteByCondition<TaiKhoan>(tk => MaTK.Where(x => x == tk.MaTK).Count() == 1);
            return Generic.DeleteByCondition<TaiKhoan>(tk => MaTK.Where(x => x == tk.MaTK).Count() == 1);
        }
        /// <summary>
        /// update Mat Khau Theo Ma TK.
        /// </summary>
        public static int updateMK(string tk, string mk)
        {
            return Generic.EditByCondition<TaiKhoan>(k => k.MaTK == tk, k =>
            {

                k.MatKhau = mk;

            });
        }
        /// <summary>
        /// update 1 tài khoản theo mã tk.
        /// </summary>
        public static ActionResult Update(TaiKhoan tk, ThongTinNguoiDung tt, string _mk2)
        {
            ActionResult act = new ActionResult("Thêm Tài Khoản");
            act.Exceptions.AddRange(TestError(tk, tt, _mk2, " ").Exceptions);
            if (act.GetErrorMessages().ToList().Count == 0)
            {
                try
                {
                    using (var transaciton = new System.Transactions.TransactionScope())
                    {
                        Generic.EditByCondition<TaiKhoan>(k => k.MaTK == tk.MaTK, k =>
                        {
                            k.MaTK = tk.MaTK;
                            k.TenDangNhap = tk.TenDangNhap;
                            k.MatKhau = tk.MatKhau;
                            k.LanCuoiDangNhap = tk.LanCuoiDangNhap;
                            k.MayDangNhap = tk.MayDangNhap;
                            k.TrangThai = tk.TrangThai;

                        });
                        if (Generic.FindByCondition<ThongTinNguoiDung>(x => x.MaTK == tt.MaTK).Count() > 0)
                            Generic.EditByCondition<ThongTinNguoiDung>(k => k.MaTK == tt.MaTK, k =>
                            {
                                k.MaTK = tt.MaTK;
                                k.Ho = tt.Ho;
                                k.Ten = tt.Ten;
                                k.NgaySinh = tt.NgaySinh;
                                k.SDT = tt.SDT;
                                k.CMND = tt.CMND;
                                k.ChucVu = tt.ChucVu;
                            });
                        else
                            Generic.Insert<ThongTinNguoiDung>(tt);

                        transaciton.Complete();
                    }
                }
                catch (Exception ex)
                {
                    act.Exceptions.Add(ex);
                }
            }
            return act;
        }
        /// Find 1 tài khoản theo ma tai khoan
        /// </summary>
        public static TaiKhoan FindByID(string mataikhoan)
        {
            return Generic.FindOneByCondition<TaiKhoan>(x => x.MaTK == mataikhoan);
        }
        /// <summary>
        /// Find 1 tài khoản theo Tên tk.
        /// </summary>
        public static TaiKhoan FindByUserName(string username)
        {
            return Generic.GetAll<TaiKhoan>().ToList().Find(x => x.TenDangNhap == username);
        }
        /// <summary>
        /// Find 1 tài khoản theo Điều Kiện.
        /// </summary>
        public static IEnumerable<TaiKhoan> FindByCondition(Func<TaiKhoan, bool> func)
        {
            return Generic.FindByCondition<TaiKhoan>(func);
        }
        public static TaiKhoan FindAccountLogin(Func<TaiKhoan, bool> func)
        {
            return Generic.FindOneByCondition<TaiKhoan>(func);
        }
        public static int Update(TaiKhoan tk)
        {
            return Generic.EditByCondition<TaiKhoan>(x => x.MaTK == tk.MaTK,
            x =>
            {
                x.MatKhau = tk.MatKhau;
                x.MayDangNhap = tk.MayDangNhap;
                x.TrangThai = tk.TrangThai;
                x.LanCuoiDangNhap = tk.LanCuoiDangNhap;
            });

        }
        /// <summary>
        /// Find Thông Tin Cá Nhân tài khoản theo mã tk.
        /// </summary>
        public static ThongTinNguoiDung FindThongTin(string MaTK)
        {
            IEnumerable<ThongTinNguoiDung> tt = Generic.FindByCondition<ThongTinNguoiDung>(x => x.MaTK == MaTK);
            return tt.Count() == 0 ? null : tt.First();
        }

        public static IEnumerable<ThongTinNguoiDung> FindThongTin(Func<ThongTinNguoiDung, bool> func)
        {
            IEnumerable<ThongTinNguoiDung> tt = Generic.FindByCondition<ThongTinNguoiDung>(x => func(x) == true);
            return tt;
        }
        /// <summary>
        /// Tim Kieem Theo Dieu Kien
        /// </summary>
        public enum DKTimKiem
        {
            MaTK = 0,
            TenDangNhap,
            TrangThai,
            LanCuoiDangNhap,
            MayDangNhap,
            HoTen,
            NgaySinh,
            CMND,
            SDT,
            ChucVu
        };

        public static void TimKiem(DataGridView dtgvQLTK, ComboBox cbbLoaiTK, DKTimKiem dk, string dktimkiem)
        {
            if (cbbLoaiTK.SelectedIndex < 5)
            {
                for (int i = 1; i < 6; i++)
                    dtgvQLTK.Columns[i].Visible = true;
                for (int i = 6; i < 12; i++)
                    dtgvQLTK.Columns[i].Visible = false;
            }
            else
            {
                for (int i = 6; i < 12; i++)
                    dtgvQLTK.Columns[i].Visible = true;
                for (int i = 1; i < 6; i++)
                    dtgvQLTK.Columns[i].Visible = false;
            }
            try
            {
                switch (dk)
                {
                    case DKTimKiem.MaTK:
                        dtgvQLTK.DataSource = QLTaiKhoan.FindByCondition(x => Regex.IsMatch(x.MaTK, dktimkiem));
                        break;
                    case DKTimKiem.TenDangNhap:
                        dtgvQLTK.DataSource = QLTaiKhoan.FindByCondition(x => Regex.IsMatch(x.TenDangNhap, dktimkiem));
                        break;
                    case DKTimKiem.TrangThai:
                        dtgvQLTK.DataSource = QLTaiKhoan.FindByCondition(x => Regex.IsMatch(x.TrangThai, dktimkiem));
                        break;
                    case DKTimKiem.LanCuoiDangNhap:
                        dtgvQLTK.DataSource = QLTaiKhoan.FindByCondition(x => Regex.IsMatch(x.LanCuoiDangNhap.Value.ToString(), dktimkiem));
                        break;
                    case DKTimKiem.MayDangNhap:
                        dtgvQLTK.DataSource = QLTaiKhoan.FindByCondition(x => Regex.IsMatch(x.MayDangNhap, dktimkiem));
                        break;
                    case DKTimKiem.HoTen:
                        dtgvQLTK.DataSource = QLTaiKhoan.FindThongTin(x => Regex.IsMatch(x.Ho, dktimkiem) || Regex.IsMatch(x.Ten, dktimkiem));
                        break;
                    case DKTimKiem.NgaySinh:
                        dtgvQLTK.DataSource = QLTaiKhoan.FindThongTin(x => Regex.IsMatch(x.NgaySinh.Value.ToShortDateString(), dktimkiem));
                        break;
                    case DKTimKiem.CMND:
                        dtgvQLTK.DataSource = QLTaiKhoan.FindThongTin(x => Regex.IsMatch(x.CMND, dktimkiem));
                        break;
                    case DKTimKiem.SDT:
                        dtgvQLTK.DataSource = QLTaiKhoan.FindThongTin(x => Regex.IsMatch(x.SDT.Value.ToString(), dktimkiem));
                        break;
                    case DKTimKiem.ChucVu:
                        dtgvQLTK.DataSource = QLTaiKhoan.FindThongTin(x => Regex.IsMatch(x.ChucVu, dktimkiem));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #region Xắp Xếp
        public static int click = 0;
        public static void XapXep(DataGridView dtgvQLTK, DataGridViewCellEventArgs e)
        {
            IEnumerable<TaiKhoan> k = null;
            IEnumerable<ThongTinNguoiDung> tt = null;

            if (dtgvQLTK.Columns[e.ColumnIndex].Name == "MaTaiKhoan" && dtgvQLTK.Columns[e.ColumnIndex + 1].Name == "TenDangNhap")
            {
                click++;
                if (click == 1)
                {
                    k = from taikhoan in GetAll().ToList()
                        orderby taikhoan.MaTK
                        select taikhoan;
                }
                else if (click == 2)
                {
                    k = from taikhoan in GetAll().ToList()
                        orderby taikhoan.MaTK descending
                        select taikhoan;
                    click = 0;
                }

                dtgvQLTK.DataSource = k.ToList();
            }
            else if (dtgvQLTK.Columns[e.ColumnIndex].Name == "TenDangNhap")
            {
                click++;
                if (click == 1)
                {
                    k = from taikhoan in GetAll().ToList()
                        orderby taikhoan.TenDangNhap
                        select taikhoan;
                }
                else if (click == 2)
                {
                    k = from taikhoan in GetAll().ToList()
                        orderby taikhoan.TenDangNhap descending
                        select taikhoan;
                    click = 0;
                }

                dtgvQLTK.DataSource = k.ToList();
            }
            else if (dtgvQLTK.Columns[e.ColumnIndex].Name == "LanCuoiDangNhap")
            {
                click++;
                if (click == 1)
                {
                    k = from taikhoan in GetAll().ToList()
                        orderby taikhoan.LanCuoiDangNhap
                        select taikhoan;
                }
                else if (click == 2)
                {
                    k = from taikhoan in GetAll().ToList()
                        orderby taikhoan.LanCuoiDangNhap descending
                        select taikhoan;
                    click = 0;
                }

                dtgvQLTK.DataSource = k.ToList();
            }
            else if (dtgvQLTK.Columns[e.ColumnIndex].Name == "Ho")
            {
                click++;
                if (click == 1)
                {
                    tt = from thongtin in Generic.GetAll<ThongTinNguoiDung>().ToList()
                         orderby thongtin.Ho
                         select thongtin;
                }
                else if (click == 2)
                {
                    tt = from thongtin in Generic.GetAll<ThongTinNguoiDung>().ToList()
                         orderby thongtin.Ho descending
                         select thongtin;
                    click = 0;
                }

                dtgvQLTK.DataSource = tt.ToList();
            }
            else if (dtgvQLTK.Columns[e.ColumnIndex].Name == "MaTaiKhoan")
            {
                click++;
                if (click == 1)
                {
                    tt = from thongtin in Generic.GetAll<ThongTinNguoiDung>().ToList()
                         orderby thongtin.MaTK
                         select thongtin;
                }
                else if (click == 2)
                {
                    tt = from thongtin in Generic.GetAll<ThongTinNguoiDung>().ToList()
                         orderby thongtin.MaTK descending
                         select thongtin;
                    click = 0;
                }

                dtgvQLTK.DataSource = tt.ToList();
            }
            else if (dtgvQLTK.Columns[e.ColumnIndex].Name == "Ten")
            {
                click++;
                if (click == 1)
                {
                    tt = from thongtin in Generic.GetAll<ThongTinNguoiDung>().ToList()
                         orderby thongtin.Ten
                         select thongtin;
                }
                else if (click == 2)
                {
                    tt = from thongtin in Generic.GetAll<ThongTinNguoiDung>().ToList()
                         orderby thongtin.Ten descending
                         select thongtin;
                    click = 0;
                }

                dtgvQLTK.DataSource = tt.ToList();
            }
            else if (dtgvQLTK.Columns[e.ColumnIndex].Name == "NgaySinh")
            {
                click++;
                if (click == 1)
                {
                    tt = from thongtin in Generic.GetAll<ThongTinNguoiDung>().ToList()
                         orderby thongtin.NgaySinh
                         select thongtin;
                }
                else if (click == 2)
                {
                    tt = from thongtin in Generic.GetAll<ThongTinNguoiDung>().ToList()
                         orderby thongtin.NgaySinh descending
                         select thongtin;
                    click = 0;
                }

                dtgvQLTK.DataSource = tt.ToList();
            }
            else if (dtgvQLTK.Columns[e.ColumnIndex].Name == "ChucVu")
            {
                click++;
                if (click == 1)
                {
                    tt = from thongtin in Generic.GetAll<ThongTinNguoiDung>().ToList()
                         orderby thongtin.ChucVu
                         select thongtin;
                }
                else if (click == 2)
                {
                    tt = from thongtin in Generic.GetAll<ThongTinNguoiDung>().ToList()
                         orderby thongtin.ChucVu descending
                         select thongtin;
                    click = 0;
                }

                dtgvQLTK.DataSource = tt.ToList();
            }
        }

        #endregion
    }
}
